package com.qxsx.midi.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qxsx.midi.R;
import com.qxsx.midi.activity.home.AdvertisementActivity;
import com.qxsx.midi.activity.study.StudyClubSearchActivity;
import com.qxsx.midi.activity.study.StudyLocalCityListActivity;
import com.qxsx.midi.adapter.ImgAdapter;
import com.qxsx.midi.adapter.StudyMainPageListAdapter;
import com.qxsx.midi.config.AppContext;
import com.qxsx.midi.model.Binner;
import com.qxsx.midi.model.StudyListItem;
import com.qxsx.midi.utils.CustomProgress;
import com.qxsx.midi.utils.MyNet;
import com.qxsx.midi.utils.SPUtils;
import com.qxsx.midi.utils.callBackJsonArray;
import com.qxsx.midi.view.MyGallery;
import com.qxsx.midi.view.XListView;
import com.qxsx.midi.view.XListView.IXListViewListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Joney on 2015/8/31.
 */
public class StudyFragment extends Fragment implements OnClickListener, IXListViewListener {
    private CustomProgress customProgress;

    private static int _page = 1; //   初始化页码为1
    private static String _city_id = "";

    public enum Page {
        StudyWhere,             // 去哪学页面
        StudyWho                // 跟谁学页面
    }

    private XListView listView;          //
    private Button btnStudyWhere;       // 去哪学按钮
    private Button btnStudyWho;         // 跟谁学按钮
    private FrameLayout btnLocate;      // title 定位按钮
    public static Page curPage;               // 当前在那个列表
    private TextView tv_city;
    private EditText edt_study_search;      //搜索框
    private StudyMainPageListAdapter listAdapter; //适配器
    private List<StudyListItem> Llist;    //“去哪儿”集合

    private List<StudyListItem> Tlist;    //“跟谁学”集合
    // 轮播图
    private MyGallery gallery = null;
    private ArrayList<Binner> imgList;
    private ArrayList<ImageView> portImg;
    private int preSelImgIndex = 0;
    private LinearLayout ll_focus_indicator_container = null;
    private ImgAdapter adapter;
    private Handler mHandler;  //执行下拉、上拉线程
    private Intent intent;

    String cityname;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_study, container, false);
        findById(v);
        // 开始抓取
        this.onClick(btnStudyWhere);
        inItData();
        mHandler = new Handler();
        return v;
    }

    private void findById(View v) {

        // Title 可见，并且设置为“学音乐”
        TextView title = (TextView) v.findViewById(R.id.study_title_txt);
        title.setVisibility(View.VISIBLE);
        title.setText("学音乐");
        // 返回
        FrameLayout btnBack = (FrameLayout) v.findViewById(R.id.study_title_btn_back);
        btnBack.setVisibility(View.GONE);
        // 定位按钮
        btnLocate = (FrameLayout) v.findViewById(R.id.study_title_btn_localte);
        btnLocate.setOnClickListener(this);
        btnLocate.setVisibility(View.VISIBLE);

        tv_city = (TextView) v.findViewById(R.id.study_txt_locate);
        tv_city.setVisibility(View.VISIBLE);
        tv_city.setTextColor(getResources().getColor(R.color.theme_green));

        // 按钮“去哪学"
        btnStudyWhere = (Button) v.findViewById(R.id.btn_where);
        btnStudyWhere.setOnClickListener(this);

        // 按钮“跟谁学"
        btnStudyWho = (Button) v.findViewById(R.id.btn_who);
        btnStudyWho.setOnClickListener(this);

        // 列表
        listView = (XListView) v.findViewById(R.id.study_list);
        listView.setXListViewListener(this);

        edt_study_search = (EditText) v.findViewById(R.id.edt_study_search);
        edt_study_search.setOnClickListener(this);

        ll_focus_indicator_container = (LinearLayout) v.findViewById(R.id.ll_focus_indicator_container);
        gallery = (MyGallery) v.findViewById(R.id.gallery);
    }

    /**
     * 初始化数据
     */
    private void inItData() {

        Llist = new ArrayList<>();
        listAdapter = new StudyMainPageListAdapter(this.getActivity(), Llist);
        listView.setAdapter(listAdapter);
        listView.setPullLoadEnable(true);
        listView.setPullRefreshEnable(true);
        getBinnerData();

    }

    @Override
    public void onRefresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                LoadRefresh();
            }
        }, 2000);
    }

    @Override
    public void onLoadMore() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                LoadMore();
            }
        }, 2000);
    }

    /**
     * 下拉刷新
     */
    private void LoadRefresh() {
        _page = 1;
        listAdapter.RemoveAll();
        if (curPage == Page.StudyWhere) {
            _page = 1;//初始化页数为1
            getLocateList(_city_id, "");
        } else if (curPage == Page.StudyWho) {
            _page = 1;//初始化页数为1
            getTeacherList(_city_id);
        }
        listView.stopRefresh();
        listView.setRefreshTime("2015-1-11");
    }

    /**
     * 上拉加载更多
     */
    private void LoadMore() {
        _page++;
        if (curPage == Page.StudyWhere) {
            getLocateList(_page, _city_id, "");
        } else if (curPage == Page.StudyWho) {
            getTeacherList(_page, _city_id);
        }
        listView.stopLoadMore();
    }

    /**
     * 获取“去哪了”列表 第一页面
     *
     * @param cityid
     */
    private void getLocateList(int page, String cityid, String site_name) {

        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();
        try {
            object.put("club_city", _city_id);
            object.put("site_name", site_name);
            object.put("nowpage", page + "");
            object.put("pagesize", 10 + "");
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("503", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                if ("200".equals(code.toString())) {
                    try {
                        Llist = new ArrayList<StudyListItem>();
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject object = array.getJSONObject(i);
                            StudyListItem sd = new StudyListItem();
                            sd.set_id(object.getString("id"));
                            sd.set_title(object.getString("exam_site_name"));
                            sd.set_desc(object.getString("address"));
                            sd.set_Tdesc("");
                            sd.set_icon(object.getString("site_icon"));
                            Llist.add(sd);
                        }
                        listAdapter.AddData(Llist);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.e("code", code.toString());
                    Log.e("message", message.toString());
                }

            }
        });

    }

    private void getLocateList(String cityid, String site_name) {

        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();
        try {
            object.put("club_city", _city_id);
            object.put("site_name", site_name);
            object.put("nowpage", 1 + "");
            object.put("pagesize", 10 + "");
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("503", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {

                if ("200".equals(code.toString())) {
                    try {
                        Llist = new ArrayList<StudyListItem>();
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject object = array.getJSONObject(i);
                            StudyListItem sd = new StudyListItem();
                            sd.set_id(object.getString("id"));
                            sd.set_title(object.getString("exam_site_name"));
                            sd.set_desc(object.getString("address"));
                            sd.set_Tdesc("");
                            sd.set_icon(object.getString("site_icon"));
                            Llist.add(sd);
                        }
                        listAdapter.RemoveAll();
                        listAdapter.AddData(Llist);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.e("code", code.toString());
                    Log.e("message", message.toString());
                }
            }
        });

    }

    /**
     * 获取“跟谁学”列表 第一页面
     *
     * @param cityid
     */
    private void getTeacherList(int page, String cityid) {

        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();
        try {
            object.put("city_id", _city_id);
            object.put("nowpage", page + "");
            object.put("pagesize", 10 + "");
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("603", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                if ("200".equals(code.toString())) {
                    try {
                        Tlist = new ArrayList<StudyListItem>();
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject object = array.getJSONObject(i);
                            StudyListItem sd = new StudyListItem();
                            sd.set_id(object.getString("id"));
                            sd.set_Tdesc(object.getString("real_name") + " " + "-" + " ");
                            sd.set_title(object.getString("major_name") + " " + "-" + " ");
                            sd.set_desc(object.getString("mr_introduce"));
                            sd.set_city(object.getString("name"));
                            if (object.getString("head_img").isEmpty()) {
                                sd.set_icon("");

                            } else {
                                sd.set_icon(object.getString("head_img"));
                            }
                            Tlist.add(sd);
                        }
                        listAdapter.AddData(Tlist);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.e("code", code.toString());
                    Log.e("message", message.toString());
                }
            }
        });

    }

    private void getTeacherList(String cityid) {

        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();
        try {
            object.put("city_id", _city_id);
            object.put("nowpage", 1 + "");
            object.put("pagesize", 10 + "");
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("603", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                if ("200".equals(code.toString())) {
                    try {
                        Tlist = new ArrayList<StudyListItem>();
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject object = array.getJSONObject(i);
                            StudyListItem sd = new StudyListItem();
                            sd.set_id(object.getString("id"));
                            sd.set_Tdesc(object.getString("real_name") + " " + "-" + " ");
                            sd.set_title(object.getString("major_name") + " " + "-" + " ");
                            sd.set_desc(object.getString("mr_introduce"));
                            sd.set_city(object.getString("name"));
                            if (object.getString("head_img").isEmpty()) {
                                sd.set_icon("");

                            } else {
                                sd.set_icon(object.getString("head_img"));
                            }
                            Tlist.add(sd);
                        }
                        listAdapter.RemoveAll();
                        listAdapter.AddData(Tlist);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.e("code", code.toString());
                    Log.e("message", message.toString());
                }

            }
        });

    }

    /**
     * 获取轮播图
     */
    private void getBinnerData() {
        customProgress = CustomProgress.show(getActivity(), "请稍后....", true, null);

        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();
        try {
            object.put("param", "no");
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("203", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                if (array == null) {
                    Log.w("array", array + "");
                } else {

                    try {
                        imgList = new ArrayList<Binner>();
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject object1 = array.getJSONObject(i);
                            Binner binner = new Binner();
                            binner.set_id(object1.getString("id"));
                            binner.set_name(object1.getString("img_name"));
                            binner.set_type(object1.getString("img_type"));
                            binner.set_url(object1.getString("img_url"));
                            binner.set_contexturl(object1.getString("img_display_url"));
                            imgList.add(binner);
                        }
                        adapter.AddDtata(imgList);
                        InitFocusIndicatorContainer();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                customProgress.dismiss();
            }
        });

        imgList = new ArrayList<Binner>();
        adapter = new ImgAdapter(getActivity(), imgList);
        gallery.setAdapter(adapter);
        gallery.setFocusable(true);
        gallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int selIndex, long arg3) {
                if (imgList.size() != 0) {


                    selIndex = selIndex % imgList.size();
                    // 修改上一次选中项的背景
                    portImg.get(preSelImgIndex).setImageResource(R.mipmap.binner_white);
                    // 修改当前选中项的背景
                    portImg.get(selIndex).setImageResource(R.mipmap.binner_green);
                    preSelImgIndex = selIndex;
                }
            }

            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
        gallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Log.e("position", position + "");
                Intent intent = new Intent();
                intent.putExtra("_url", imgList.get(position % imgList.size()).get_contexturl());
                intent.setClass(getActivity(), AdvertisementActivity.class);
                startActivity(intent);

            }

        });
    }

    /**
     * 轮播图的小圆标
     */
    private void InitFocusIndicatorContainer() {
        portImg = new ArrayList<ImageView>();
        for (int i = 0; i < imgList.size(); i++) {
            ImageView localImageView = new ImageView(getActivity());
            localImageView.setId(i);
            ImageView.ScaleType localScaleType = ImageView.ScaleType.FIT_XY;
            localImageView.setScaleType(localScaleType);
            LinearLayout.LayoutParams localLayoutParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            localImageView.setLayoutParams(localLayoutParams);
            localImageView.setPadding(0, 0, 8, 0);
            localImageView.setImageResource(R.mipmap.binner_white);
            if (i == 0) {
                localImageView.setImageResource(R.mipmap.binner_green);
            } else {
                localImageView.setImageResource(R.mipmap.binner_white);
            }
            portImg.add(localImageView);
            this.ll_focus_indicator_container.addView(localImageView);
        }
    }

    // 切换 在哪学，跟谁学
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btn_where:
                btnStudyWho.setSelected(false);
                btnStudyWhere.setSelected(true);
                curPage = Page.StudyWhere;
                _page = 1;//初始化页数为1
                Llist = new ArrayList<>();
                listAdapter = new StudyMainPageListAdapter(this.getActivity(), Llist);
                listView.setAdapter(listAdapter);
                getLocateList(_city_id, "");
                break;
            case R.id.btn_who:
                btnStudyWhere.setSelected(false);
                btnStudyWho.setSelected(true);
                curPage = Page.StudyWho;
                _page = 1;//初始化页数为1
                Llist = new ArrayList<>();
                listAdapter = new StudyMainPageListAdapter(this.getActivity(), Llist);
                listView.setAdapter(listAdapter);
                getTeacherList(_city_id);
                break;
            case R.id.study_title_btn_localte:
                // 定位 club 城市
                if (curPage == Page.StudyWhere) {
                    Log.e("StudyFragment", "130");
                } else {    // 定位 Midi 先生城市
                    Log.e("StudyFragment", "132");
                }
                // 切换到定位UI
                intent = new Intent(this.getActivity(), StudyLocalCityListActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("id", "1");
                intent.putExtras(bundle);
                this.startActivity(intent);
                break;
            case R.id.edt_study_search:
                intent = new Intent();
                if (curPage == Page.StudyWhere) {
                    intent.putExtra("_Tag", "Where");
                } else if (curPage == Page.StudyWho) {
                    intent.putExtra("_Tag", "Who");
                }
                intent.setClass(getActivity(), StudyClubSearchActivity.class);
                getActivity().startActivity(intent);

                break;

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        _city_id = (String) SPUtils.get(AppContext.getContext(), "chooes_city_id", "");
        cityname = (String) SPUtils.get(AppContext.getContext(), "chooes_city_name", "");
        tv_city.setText(cityname);
        if (curPage == Page.StudyWhere) {
            getLocateList(_city_id, "");
        } else if (curPage == Page.StudyWho) {
            getTeacherList(_city_id);
        }
    }
}


